<template>
  <div id="app">
    <h1>购物车</h1>
    <div v-for="item in cartItems" :key="item.id">
      <cart-item :item="item" />
    </div>
    <cart-total />
    <div class="add-item">
      <input v-model="newItem.name" placeholder="商品名称">
      <input v-model.number="newItem.price" type="number" placeholder="价格">
      <button @click="addItem">添加商品</button>
    </div>
  </div>
</template>

<script>
import CartItem from './components/CartItem.vue'
import CartTotal from './components/CartTotal.vue'
import { mapState } from 'vuex'

export default {
  name: 'App',
  components: {
    CartItem,
    CartTotal
  },
  data() {
    return {
      newItem: {
        name: '',
        price: 0
      }
    }
  },
  computed: {
    ...mapState(['cartItems'])
  },
  methods: {
    addItem() {
      if (this.newItem.name && this.newItem.price > 0) {
        this.$store.dispatch('addItem', {
          id: Date.now(),
          ...this.newItem
        })
        this.newItem = { name: '', price: 0 }
      }
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}
.add-item {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}
input {
  padding: 5px;
}
</style>